// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const obj = uniCloud.importObject('uni-id-co')
const uniID  = require('uni-id')
const { handleParams,handleQuery } = require('handle-params')
module.exports = {
	_before: function () { // 通用预处理器
		let clientInfo = this.getClientInfo();
		let httpInfo = this.getHttpInfo();
		if(httpInfo && httpInfo.body){//第三方应用参数处理 添加this.reqParams
			let data = {}
			if(httpInfo.body.includes('=') || httpInfo.body.includes('&')){
				data = handleQuery(httpInfo.body)
			}else{
				data = JSON.parse(httpInfo.body)
			}
			let clientInfo = {
				APPID:data.APPID,
				LOCALE:'zh-Hans',
				PLATFORM:'h5',
				appId:data.APPID
			}
			this.uniID = uniID.createInstance({
				clientInfo
			})	
			this.reqParams = handleParams(data);
		}else{
			this.uniID = uniID.createInstance({
				clientInfo
			})	
		}
		
	},
	_timing:function () {
		
	},
	/**
	 * 获取第三方情话接口
	 */
	async getLoveWords(){
		const data = await uniCloud.httpclient.request('http://api.1314.cool/words/api.php?return=json',{
			dataType:'json',
			method:'GET'
		})
		const db = uniCloud.database().collection('love-words');
		let res = await db.where({
			text:data.data.word
		}).count()
		if(res.total == 0 && data.data.word){
			db.add({
				time:Date.now(),
				text:data.data.word
			})
		}
		return {
			code:200,
			text:data.data.word
		}
	},
	async login(params){
		if(this.reqParams) params = this.reqParams
		return await this.uniID.login(params)
	},
	async register(params){
		if(this.reqParams) params = this.reqParams
		return await this.uniID.register(params)
	},
	
	/*
	*新增
	*/
	async addLoverWord(params){
		const db = uniCloud.database().collection('love-words');
		if(this.reqParams) params = this.reqParams
		params.text = params.text.replace(/(^\s*)|(\s*$)/g,"")
		if(!params.text){
			return {
				code:400,
				msg:'参数必填'
			}
		}
		let obj = {
			time:Date.now()
		}
		let res = await db.where({
			text:params.text
		}).count()
		if(res.total){
			return {
				code:400,
				msg:'有重复'
			}
		}else{
			await db.add({
				...params,
				...obj
			})
		}
		
		return {
			code:200,
			msg:'添加成功'
		}
	},
	/**
	 * 获取列表
	 */
	async loveWordList(params = {}){
		const db = uniCloud.database().collection('love-words');
		if(this.reqParams) params = this.reqParams;
		let page = params.page?Number(params.page):1;
		let pageSize = params.pageSize?Number(params.pageSize):10;
		let skip = (page -1) * pageSize;
		let res = await db.skip(skip).limit(pageSize).orderBy('time','desc').get();
		let info = await db.count();
		return {
			code:200,
			data:{
				list:res.data,
				total:info.total
			},
			msg:''
		}
	}
}

